/**
 * create by young (young2f@outlook.com) on 2020/9/12
 */


'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Form, Input, Popconfirm, Table} from 'antd';
import styles from '../index.less';
import {FormField, ModalView, SearchForm} from 'antd-extra';

import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import ModalCreateOrEditMaterial from "./modal/ModalCreateOrEditMaterial";
import moment from "moment";

const _ = require('lodash');

const table = 'Material';

@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            treeNode
          }) => ({...user, ...global, ...material, ...dynamicLabel, ...treeNode}))
export default class Material extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    this.props.dispatch({
      type: 'material/findMany',
      payload
    });
    this.props.dispatch({
      type: 'store/statistics',
      payload
    });
  }

  onDeleteMaterial = record => {
    const {code} = record;
    this.props.dispatch({
      type: 'material/deleteOne',
      payload: {code, tenantCode: this.getTenantCode()}
    })
      .then(res => {
        this.componentDidMount();
      });
  };

  onCreateOrEditMaterial = async (material, isCopy) => {
    const {dispatch} = this.props;
    let title = material ? '编辑物料' : '新建物料';
    title = isCopy ? '复制物料' : title;
    const code = isCopy ? "MAT" + moment().format('YYYYMMDDHHmmss') : undefined;
    const values = material ? material : {code};
    if (isCopy) values.code = code;
    // if (!material) {
    //   const res = await dispatch({
    //     type: 'global/getCode',
    //     payload: {prefix: 'MAT'}
    //   });
    //   values.code = res.code;
    // }
    ModalView.open(ModalCreateOrEditMaterial, {
      title,
      width: '920px'
    }, {
      values,
      codePrefix: 'MAT',
      dispatch: dispatch,
      table: 'material',
      title: '物料',
      disabledProps: ['code'],
      callback: (data) => {
        data.createUser = this.getLoginUser();
        data.createUsername = this.getLoginUsername();
        data.tenantCode = this.getTenantCode();

        if (material && !isCopy) {
          this.props.dispatch({
            type: 'material/updateOne',
            payload: data
          }).then(res => {
            this.componentDidMount();
          });
          return;
        }

        this.props.dispatch({
          type: 'material/create',
          payload: data
        }).then(res => {
          this.componentDidMount();
        });
      }
    });
  };

  columns = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const {labels = []} = model;
    let temp = [
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code'
      },
      {
        title: '物料名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '物料规格',
        dataIndex: 'spec',
        key: 'spec'
      },
      {
        title: '物料类别',
        dataIndex: 'type',
        key: 'type'
      },
      {
        title: '物料型号',
        dataIndex: 'number',
        key: 'number'
      },
      {
        title: '形态',
        dataIndex: 'subcategory',
        key: 'subcategory'
      },
      {
        title: '品牌',
        dataIndex: 'brand',
        key: 'brand'
      },
      {
        title: '可用数量',
        dataIndex: 'procureCount',
        key: 'procureCount'
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit'
      }
    ];
    const temp1 = this.getDynamicLabelCols(labels);
    temp = _.concat(temp, temp1);
    temp.push(
      {
        title: '创建者',
        dataIndex: 'createUsername',
        key: 'createUsername',
        width: 160
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160,
        render: (value, record) => {
          return (
            <span>
              {<a style={{marginRight: '6px'}} onClick={() => this.onCreateOrEditMaterial(record)}>编辑</a>}
              {/*{<a style={{marginRight: '6px'}} onClick={() => this.setState({showDetail: true, record})}>详情</a>}*/}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => this.onDeleteMaterial(record)}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}}>删除</a>
              </Popconfirm>
              }
              {<a onClick={() => this.onCreateOrEditMaterial(record,true)}>复制</a>}
            </span>
          );
        }
      });
    return temp;
  };
  getSearchFields = () => {
    const title = "物料";
    const arr = [
      <FormField
        label="编码"
        name="code"
        key={1}
      >
        <Input allowClear placeholder={`请输入${title}编码`}/>
      </FormField>,
      <FormField
        label="物料名称"
        name="name"
        key={2}
      >
        <Input allowClear placeholder={`请输入${title}名称`}/>
      </FormField>,
      <FormField
        label="物料规格"
        name="spec"
        key={3}
      >
        <Input allowClear placeholder={`请输入${title}规格`}/>
      </FormField>,
      <FormField
        label="物料编号"
        name="number"
        key={4}
      >
        <Input allowClear placeholder={`请输入${title}编号`}/>
      </FormField>,
      <FormField
        label="形态"
        name="subcategory"
        key={5}
      >
        <Input allowClear placeholder={`请输入${title}形态`}/>
      </FormField>

    ];
    return arr;

  };

  render() {
    const {materials, _notify, form} = this.props;
    const {showDetail} = this.state;
    console.log('_notify', _notify);
    if (_notify) {
      notify(_notify);
    }

    return (
      <Form className={styles.content}>

        <ViewTitle
          title={'物料列表'}
          level={1}
          actions={<Button type="primary"
                           onClick={() => this.onCreateOrEditMaterial(undefined)}>添加</Button>}></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>

        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.columns()}
          dataSource={materials}
          // scroll={{ x: true }}
          pagination={true}
        ></Table>

        {/*{showDetail && <Drawer*/}
        {/*  visible={showDetail}*/}
        {/*  title='物料详情'*/}
        {/*  placement="left"*/}
        {/*  width={'80%'}*/}
        {/*  style={{padding: 0}}*/}
        {/*  onClose={() => {*/}
        {/*    this.setState({showDetail: false});*/}
        {/*  }}*/}
        {/*>*/}
        {/*  <div>待开发</div>*/}
        {/*  /!*<ModalMaterialLots*!/*/}
        {/*  /!*  record={record}*!/*/}
        {/*  /!*  dispatch={this.props.dispatch}*!/*/}
        {/*  /!*></ModalMaterialLots>*!/*/}
        {/*</Drawer>}*/}
      </Form>
    );
  }
}
